namespace AltNetUK.Models
{
    using System;
    using System.Text;
    using System.Xml.Serialization;
    using System.Globalization;

    [XmlRoot(ElementName = "analytics")]
    public sealed class Analytics
    {
        public static implicit operator string(Analytics analytics)
        {
            return (null == analytics) ? null as string : analytics.ToString();
        }

        [XmlAttribute(AttributeName = "enabled")]
        public bool Enabled
        {
            get;
            set;
        }

        [XmlAttribute(AttributeName = "google")]
        public string Google
        {
            get;
            set;
        }

        public override string ToString()
        {
            StringBuilder buffer = new StringBuilder();

            if (this.Enabled)
            {
                buffer.AppendLine("<div id='analytics'>");
                if (!string.IsNullOrEmpty(this.Google))
                {
                    buffer.AppendLine("<script type='text/javascript'>");
                    buffer.AppendLine("var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");");
                    buffer.AppendLine("document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));");
                    buffer.AppendLine("</script>");
                    buffer.AppendLine("<script type='text/javascript'>");
                    buffer.AppendLine("try {");
                    buffer.AppendLine(string.Format(CultureInfo.InvariantCulture, "var pageTracker = _gat._getTracker(\"{0}\");", this.Google));
                    buffer.AppendLine("pageTracker._trackPageview();");
                    buffer.AppendLine("} catch(err) {}</script>");
                }

                buffer.AppendLine("</div>");
            }
            
            return buffer.ToString();
        }
    }
}